﻿using SF.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.finance
{
    public partial class finance_settlement_current : Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string action = string.Empty;
        protected string keywords = string.Empty;

        protected string settleNum = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.keywords = DTRequest.GetQueryString("keywords");
            this.action = DTRequest.GetQueryString("action");
            this.settleNum = DTRequest.GetQueryString("settleNum");
            this.hdSettleNum.Value = settleNum;
            
            if (string.IsNullOrEmpty(this.settleNum) == false)
            {
                BLL.sf_finance_settlement bll = new BLL.sf_finance_settlement();
                Model.sf_finance_settlement model = bll.GetModel(this.settleNum);
                this.lbsettlement_num.Text = this.settleNum;
                this.lboperator.Text = model.user_name;
                this.lbcreate_time.Text = model.create_time.ToString();
                this.lbtotal.Text = model.total_amount.ToString();
            }

            if (this.action == "CreateSettlement")
            {
                //生成财务结算单
                CreateSettlement();
            }


            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("app_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                RptBind("  sf_finance_settlement_num = '" + settleNum + "' and id>0" + CombSqlTxt(this.keywords), "id desc");
            }
        }


        #region CreateSettlement
        private void CreateSettlement() 
        {
            string beginTime = DTRequest.GetString("begintime");
            string endTime = DTRequest.GetString("endtime");
            string nowTime = DateTime.Now.ToString("yyyy-MM-dd");
            string msg = string.Empty;

            if (string.IsNullOrEmpty(beginTime) || string.IsNullOrEmpty(endTime))
            {
                msg = "请选择结算日期！";
            }
            else
            {
                DateTime dtBeginTime = DateTime.Parse(beginTime);
                DateTime dtEndTime = DateTime.Parse(endTime);
                DateTime dtNowTime = DateTime.Parse(nowTime);

                //开始时间必须在结束时间之前
                if (dtBeginTime < dtEndTime)
                {
                    //结算结束时间必须在今天之前
                    if (dtEndTime >= dtNowTime)
                    {
                        msg = "结算结束时间必须在今天之前！";
                    }
                    else
                    {
                        BLL.sf_finance_settlement bllf = new BLL.sf_finance_settlement();
                        Model.sf_finance_settlement modelf = bllf.GetLastModel();

                        //之前已有结算单,需要验证结算时间是否重复
                        if (modelf != null)
                        {
                            string[] temp_times = modelf.settlement_num.Replace("HT", "").Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                            temp_times[0] = temp_times[0].Insert(4, "-");
                            temp_times[0] = temp_times[0].Insert(7, "-");

                            temp_times[1] = temp_times[1].Insert(4, "-");
                            temp_times[1] = temp_times[1].Insert(7, "-");

                            DateTime temp_dtBeginTime = DateTime.Parse(temp_times[0]);
                            DateTime temp_dtEndTime = DateTime.Parse(temp_times[1]);


                            //只要是当前开始时间比上一批次的结束时间早，则不能生成
                            if (dtBeginTime <= temp_dtEndTime)
                            {
                                msg = "当前结算时间可能与以往批次的结算时间重复，请检查后重新设置！";
                            }
                            else
                            {
                                //TODO:开始结算
                                StartSettlement(dtBeginTime, dtEndTime, out msg);
                            }
                        }
                        else
                        {
                            //TODO:开始结算
                            StartSettlement(dtBeginTime, dtEndTime, out msg);
                        }
                    }
                }
                else
                {
                    msg = "开始时间必须在结束时间之前！";
                }
            }

            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "No-Cache");

            Response.Clear();
            if (string.IsNullOrEmpty(msg) == false)
            {
                Response.Write("{msg:'" + msg + "'}");
            }
            else if(string.IsNullOrEmpty(this.settleNum) == false)
            {
                Response.Write("{msg:'',settleNum:'"+this.settleNum+"'}");
            }
            Response.End();
        }

        private void StartSettlement(DateTime dtBeginTime , DateTime dtEndTime,out string msg) 
        {
            msg = "";
            Model.manager loginUser = GetAdminInfo();
            string username = loginUser == null ? "" : loginUser.real_name;


            string beginTime = dtBeginTime.ToString("yyyy-MM-dd")+" 00:00:00.000";
            string endTime = dtEndTime.ToString("yyyy-MM-dd")+" 23:59:59.999";
            string settlement_num = "HT" + dtBeginTime.ToString("yyyyMMdd") + "-" + dtEndTime.ToString("yyyyMMdd");

            BLL.sf_goods_order bllg = new BLL.sf_goods_order();
            System.Data.DataSet dsOrders = bllg.GetFinanceOrderList(" o.paytime >= '"+beginTime+"' and o.paytime <= '"+endTime+"' order by o.appNum");

            //需要结算的服务号列表以及商户列表
            string str_appNum_list = string.Empty;
            string str_businessNum_list = string.Empty;
            List<string> appNum_list = new List<string>();
            List<string> businessNum_list = new List<string>();

            if (dsOrders.Tables[0].Rows.Count > 0)
            {
                foreach (System.Data.DataRow r in dsOrders.Tables[0].Rows)
                {
                    if (str_businessNum_list.IndexOf(r["busnieseNum"].ToString()) == -1)
                    {
                        str_businessNum_list += "'" + r["busnieseNum"] + "',";
                        businessNum_list.Add(r["busnieseNum"].ToString());
                    }

                    if (str_appNum_list.IndexOf(r["appNum"].ToString()) == -1)
                    {
                        str_appNum_list += "'" + r["appNum"] + "',";
                        appNum_list.Add(r["appNum"].ToString());
                    }                    
                }

                if (str_businessNum_list.Length > 0)
                {
                    str_businessNum_list = str_businessNum_list.Remove(str_businessNum_list.Length - 1, 1);
                }
                if (str_appNum_list.Length > 0)
                {
                    str_appNum_list = str_appNum_list.Remove(str_appNum_list.Length - 1, 1);
                }


                //子合同列表
                BLL.sf_contract_child bllcc = new BLL.sf_contract_child();
                System.Data.DataSet cc_list = bllcc.GetList(" appNum in (" + str_appNum_list + ") ");

                System.Data.DataSet dsFinance = new BLL.sf_finance_settlement().GetList(" id = 0 ");
                System.Data.DataSet dsBusiness = new BLL.sf_business_settlement().GetList(" id = 0 ");
                System.Data.DataSet dsApp = new BLL.sf_businessapp_settlement().GetList(" id = 0 ");
                System.Data.DataSet dsOrder = new BLL.sf_ordersettlement().GetList(" id = 0 ");
                System.Data.DataTable dtFinance = dsFinance.Tables[0];
                System.Data.DataTable dtBusiness = dsBusiness.Tables[0];
                System.Data.DataTable dtApp = dsApp.Tables[0];
                System.Data.DataTable dtOrder = dsOrder.Tables[0];

                dtOrder.Columns.Add("businessName");
                dtOrder.Columns.Add("appName");
                dtOrder.Columns.Add("templatesName");
                dtOrder.Columns.Add("contract_num");


                //对每笔订单进行结算
                string count_appNum = string.Empty;
                string count_appName = string.Empty;
                string businessNum = string.Empty;
                string businessName = string.Empty;
                string templatesNum = string.Empty;
                string templatesName = string.Empty;
                string contract_num = string.Empty;
                int pay_type = 0;
                decimal price_one = 0;
                decimal price_low = 0;
                decimal price_low_one = 0;
                decimal price_height = 0;
                decimal price_height_two = 0;

                foreach (System.Data.DataRow r in dsOrders.Tables[0].Rows)
                { 
                    string appNum = r["appNum"].ToString();
                    string order_num = r["orderNum"].ToString();
                    decimal totalMoney = decimal.Parse(r["totalMoney"].ToString());
                    decimal amount = 0;
                    string settlement_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    if (count_appNum != appNum)
                    {
                        count_appNum = appNum;
                        count_appName = r["appid_name"].ToString();
                        businessNum = r["busnieseNum"].ToString();
                        businessName = r["real_name"].ToString();
                        templatesNum = r["templatesNum"].ToString();
                        templatesName = r["settingname"].ToString();

                        System.Data.DataRow[] cc_rows = cc_list.Tables[0].Select("appNum='" + appNum + "'");
                        if (cc_rows.Length > 0)
                        {
                            contract_num = cc_rows[0]["contract_num"].ToString();
                            pay_type = int.Parse(cc_rows[0]["pay_type"].ToString());
                            if (pay_type == 0) 
                            { 
                                price_one = decimal.Parse(cc_rows[0]["price_one"].ToString());
                            }
                            else if (pay_type == 1) 
                            { 
                                price_low = decimal.Parse(cc_rows[0]["price_low"].ToString());
                                price_low_one = decimal.Parse(cc_rows[0]["price_low_one"].ToString());
                                price_height = decimal.Parse(cc_rows[0]["price_height"].ToString());
                                price_height_two = decimal.Parse(cc_rows[0]["price_height_two"].ToString());
                            }
                        }
                    }

                    //按每笔收费
                    if (pay_type == 0)
                    {
                        amount = (decimal)price_one;
                    }
                    //按金额额度设定收费
                    else if (pay_type == 1)
                    {
                        //低于等于多少，每笔订单收多少，也就是每笔订单最少要收取的费用
                        amount = price_low_one;
                        //高出的部分按额度进行收费
                        if (totalMoney > price_low) 
                        {
                            decimal moreMoney = totalMoney - price_low;
                            if (moreMoney % price_height == 0)
                            {
                                amount += ((int)(moreMoney / price_height)) * price_height_two;
                            }
                            else 
                            {
                                amount += ((int)(moreMoney / price_height) + 1) * price_height_two;
                            }
                        }
                    }

                    System.Data.DataRow or = dtOrder.NewRow();
                    or["appNum"] = count_appNum;
                    or["appName"] = count_appName;
                    or["busnieseNum"] = businessNum;
                    or["businessName"] = businessName;                    
                    or["templatesNum"] = templatesNum;
                    or["templatesName"] = templatesName;
                    or["contract_num"] = contract_num;

                    or["sf_finance_settlement_num"] = settlement_num;
                    or["order_num"] = order_num;
                    or["payMoney"] = totalMoney;
                    or["amount"] = amount;
                    or["settlement_time"] = settlement_time;

                    dtOrder.Rows.Add(or);

                }

                //服务号结算
                foreach (string appNum in appNum_list) 
                {
                    System.Data.DataRow[] rows = dtOrder.Select("appNum='" + appNum + "'");
                    count_appName = rows[0]["appName"].ToString();
                    businessNum = rows[0]["busnieseNum"].ToString();
                    businessName = rows[0]["businessName"].ToString();
                    templatesNum = rows[0]["templatesNum"].ToString();
                    templatesName = rows[0]["templatesName"].ToString();
                    contract_num = rows[0]["contract_num"].ToString();
                    
                    decimal total_amount = 0;
                    foreach (System.Data.DataRow r in rows) 
                    {
                        total_amount += decimal.Parse(r["amount"].ToString());
                    }

                    System.Data.DataRow or = dtApp.NewRow();
                    or["sf_finance_settlement_num"] = settlement_num;
                    or["busnieseNum"] = businessNum;
                    or["business_name"] = businessName;
                    or["appNum"] = appNum;
                    or["appid_name"] = count_appName;
                    or["templatesNum"] = templatesNum;
                    or["templates_name"] = templatesName;
                    or["sf_contract_num"] = contract_num;
                    or["settlement_times"] = settlement_num.Replace("HT","");
                    or["user_name"] = username;
                    or["total_amount"] = total_amount;
                    or["create_time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    dtApp.Rows.Add(or);
                }

                //商户结算
                foreach (string bNum in businessNum_list)
                {
                    System.Data.DataRow[] rows = dtOrder.Select("busnieseNum='" + bNum + "'");
                    contract_num = rows[0]["contract_num"].ToString();

                    decimal total_amount = 0;
                    foreach (System.Data.DataRow r in rows)
                    {
                        total_amount += decimal.Parse(r["amount"].ToString());
                    }

                    System.Data.DataRow or =  dtBusiness.NewRow();
                    or["sf_finance_settlement_num"] = settlement_num;
                    or["busnieseNum"] = bNum;
                    or["businessName"] = rows[0]["businessName"].ToString();
                    or["sf_contract_num"] = contract_num;
                    or["settlement_times"] = settlement_num.Replace("HT", "");
                    or["user_name"] = username;
                    or["total_amount"] = total_amount;
                    or["state"] = "0";
                    or["pay_num"] = "";
                    //or["pay_time"] = dt;
                    or["notice_count"] = 0;
                    or["create_time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    dtBusiness.Rows.Add(or);
                }


                //财务总结算
                System.Data.DataRow fRow = dtFinance.NewRow();
                decimal f_amount = 0;
                foreach (System.Data.DataRow r in dtOrder.Rows) 
                {
                    f_amount += decimal.Parse(r["amount"].ToString());
                }

                fRow["settlement_num"] = settlement_num;
                fRow["user_name"] = username;
                fRow["total_amount"] = f_amount;
                fRow["received"] = 0;
                fRow["not_received"] = f_amount;
                fRow["state"] = "0";
                fRow["create_time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                dtFinance.Rows.Add(fRow);

                BLL.sf_finance_settlement bllf = new BLL.sf_finance_settlement();
                if (bllf.SaveSettlementResult(dtFinance, dtBusiness, dtApp, dtOrder) == false)
                {
                    msg = "结算单未生成成功，请重新尝试！";
                }
                else 
                {
                    this.settleNum = settlement_num;
                }
            }
            else 
            {
                msg = "您所选择的时间段内没有订单，不能进行结算。";
            }
        }
        #endregion

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            BLL.sf_business_settlement bll = new BLL.sf_business_settlement();
            this.rptList.DataSource = bll.GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("finance_settlement_current.aspx", "keywords={0}&page={1}", this.keywords, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (busnieseNum like '%" + _keywords + "%' or settlement_times like '%" + _keywords + "%' or user_name like '%" + _keywords + "%')");
            }

            return strTemp.ToString();
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("finance_settlement_current", "DTcmsPage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //Response.Redirect(Utils.CombUrlTxt("finance_settlement_current.aspx", "keywords={0}", txtKeywords.Text));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("finance_settle_page_size", "DTcmsPage", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("finance_settlement_current.aspx", "keywords={0}", this.keywords));
        }
    }
}